package cn.dy.workatten.imp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.dy.base.framework.esb.def.RepMessage;
import cn.dy.workatten.WorkAttenModuleImp;
import cn.dy.workatten.dao.AttendApplicationDao;
import cn.dy.workatten.dao.AttendRecordDao;
import cn.dy.workatten.dao.AuditingDetailDao;
import cn.dy.workatten.dao.AuditingFlowDao;
import cn.dy.workatten.dao.ContactInfoDao;
import cn.dy.workatten.dao.ScheduleCfgDao;
import cn.dy.workatten.dao.WorkDayDao;
import cn.dy.workatten.pojo.AttendApplication;
import cn.dy.workatten.pojo.AttendRecord;
import cn.dy.workatten.pojo.AuditingDetail;
import cn.dy.workatten.pojo.AuditingFlow;
import cn.dy.workatten.pojo.DayModel;
import cn.dy.workatten.pojo.MemberInfo;
import cn.dy.workatten.pojo.ScheduleCfg;
import cn.dy.workatten.service.WorkAttenService;
import cn.dy.workatten.util.DateUtil;

public class WorkAttenServiceImpl implements WorkAttenService {

	protected static Logger logger = LoggerFactory.getLogger(WorkAttenServiceImpl.class);
	private AttendApplicationDao attendApplicationDao;
	private AttendRecordDao attendRecordDao;
	private AuditingDetailDao auditingDetailDao;
	private AuditingFlowDao auditingFlowDao;
	private ContactInfoDao contactInfoDao;
	private WorkDayDao workDayDao;
	private ScheduleCfgDao scheduleCfgDao;
	

	public WorkAttenServiceImpl() {
	   this.attendApplicationDao = new AttendApplicationDao();
	   this.attendRecordDao = new AttendRecordDao();
	   this.auditingDetailDao = new AuditingDetailDao();
	   this.auditingFlowDao = new AuditingFlowDao();
	   this.contactInfoDao = new ContactInfoDao();
	   this.workDayDao = new WorkDayDao();
	   this.scheduleCfgDao = new ScheduleCfgDao();
	}


	@Override
	public RepMessage getContactInfoByDept(long dept_id, String query, long pageNum, long pageSize) {
		// 根据部门查询用户列表，ecc_contact_holder关联表，关联 员工表（ecc_contact_info）和 部门表（ecc_contact_group），GROUP_ID就是dept_id
		RepMessage repMessage = new RepMessage();
		try {
			Map<String, Object> map = new HashMap();
			map.put("result",
					this.contactInfoDao.getMemberListByDept(dept_id, query, (int)pageNum, (int)pageSize));
			map.put("total",
					this.contactInfoDao.getMemberListByDeptCount(dept_id, query));
			repMessage.setContent(map);
			repMessage.setResponse_code("0");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("条件查询日志失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.warn("条件查询日志失败");
		}
		return repMessage;
	}
	

	@Override
	public RepMessage createNewWorkAtten(long dept_id, String dateStr, String[] staff_Ids, String[] schedule_Ids,
			String[] man_hour_midnights, String[] work_values, long audit1, long audit2, long audit3, long audit4,
			long audit5, long saveAndCommit) {
		// 新增考勤，插入bz_attend_application一条数据，插入bz_attend_record多条数据，插入一条bz_auditing_flow，
		// 插入多条bz_auditing_detail，设置了几个审批人员就有几条记录，记录之间上一流程和下一流程之间互相关联
		
		RepMessage repMessage = new RepMessage();
		try {
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat df2 = new SimpleDateFormat("yyyyMM");
			SimpleDateFormat df3 = new SimpleDateFormat("dd");
			SimpleDateFormat df4 = new SimpleDateFormat("yyyyMMdd");
			Date genDate = df.parse(dateStr);
			genDate.setHours(0);
			genDate.setMinutes(0);
			genDate.setSeconds(0);
			
			long month = DateUtil.getDateMonth(genDate);
			int year = DateUtil.getDateYear(genDate);
			int day = DateUtil.getDateDay(genDate);
			
			long yearMonth = Long.parseLong(df2.format(genDate));
			String attendance_days = df3.format(genDate);
			
			// 判断这个部门这个日期的考勤是否已经存在过
			int isExist = this.attendApplicationDao.isExistAttendApplication(dept_id, yearMonth, attendance_days);
			if(isExist > 0) {
				repMessage.setResponse_code("-2");
				repMessage.setResponse_desc("该日期考勤已存在");
				return repMessage;
			}
			
			Date nowDate = new Date();
			// 插入bz_attend_application一条数据
			AttendApplication attendApplication = new AttendApplication();
			long application_id = this.attendApplicationDao.getUniqueId();
			attendApplication.setId(application_id);
			attendApplication.setAttendance_days(attendance_days);
			attendApplication.setAttendance_month(yearMonth);
			int user_id = Integer.parseInt(WorkAttenModuleImp.context.getContextByName("user_id").toString());
			
			attendApplication.setCreate_id(user_id);
			attendApplication.setCreate_time(nowDate);
			attendApplication.setDept_id(dept_id);
			attendApplication.setSts("0"); // 状态0初始1审批中2结束
			this.attendApplicationDao.addAttendApplication(attendApplication);
			
			// 获得公司id
			int corp_id = 0;
			if (WorkAttenModuleImp.context.getContextByName("corp_id") != null) {
				  corp_id = Integer.parseInt(WorkAttenModuleImp.context.getContextByName("corp_id").toString());
			}
			
			// 查询某个年份，某个公司的日历
			DayModel yearCalendar = this.workDayDao.queryYearCalendar(corp_id, String.valueOf(year));
			
			// 查询某个日期，属于那种类型的加值班
			DayModel workDay = this.workDayDao.queryForDate(df4.format(genDate), yearCalendar.getId());
			int genDayType = Integer.parseInt(workDay.getDayType());
			int wday_id = Integer.parseInt(workDay.getId());
			
			if(genDayType == 0) { // 法定工作日情况，
				// 判断这个日期是工作日，还是周末，
				// 获得这个日期是星期几
				int dayOfWeek = DateUtil.getDayForWeek(genDate);
				DayModel weekDay = this.workDayDao.queryWeekDay(wday_id, dayOfWeek);
				if(weekDay.getOtimeId().equals("1")) { // 工作日
					
				} else {// 周末, 设置genDayType为4
					genDayType = 4;
				}
			}
			
			// 根据genDayType查询bz_schedule_cfg表所有记录
			List<ScheduleCfg> genDayScheduleList = this.scheduleCfgDao.getScheduleCfgByType(genDayType);
			
			// 插入bz_attend_record多条数据
			for(int i = 0; i < staff_Ids.length; i++) {
				String oneStaffId = staff_Ids[i];
				AttendRecord oneAttendRecord = new AttendRecord();
				oneAttendRecord.setCreate_id(user_id);
				oneAttendRecord.setCreate_time(nowDate);
				oneAttendRecord.setDept_id(dept_id);
				oneAttendRecord.setAttend_day(genDate);
				oneAttendRecord.setStaff_id(Long.parseLong(oneStaffId));
//				oneAttendRecord.setMan_hour_all(man_hour_all);
				oneAttendRecord.setMan_hour_midnight(Long.parseLong(man_hour_midnights[i]));
				oneAttendRecord.setWork_value(work_values[i]);
				
//				oneAttendRecord.setSchedule_id(Long.parseLong(schedule_Ids[i]));
				
				if(schedule_Ids[i] != null && !schedule_Ids[i].isEmpty()) {
					
					// 判断这个员工被勾选的，对应bz_schedule_cfg表中schedule_sub_type包含哪一个，就增加一个这个setSchedule_id的AttendRecord记录
					for(ScheduleCfg oneScheduleCfg : genDayScheduleList) {
						// 判断这个值班子类型，是否被勾选了，如果被勾选了，就增加一条AttendRecord记录
//						String[] subTypeArr = oneScheduleCfg.getSchedule_sub_type().split(",");
//						for(String oneSubType : subTypeArr) {
//							if(schedule_Ids[i].contains(oneSubType)) {
//								oneAttendRecord.setSchedule_id(oneScheduleCfg.getId());
//								this.attendRecordDao.addAttendRecord(oneAttendRecord);
//								break;
//							}
//						}
						if(schedule_Ids[i].contains(oneScheduleCfg.getSchedule_sub_type())) {
							oneAttendRecord.setSchedule_id(oneScheduleCfg.getId());
							this.attendRecordDao.addAttendRecord(oneAttendRecord);
							break;
						}
						
					}
				}
			}
			
			long flow_id = this.auditingFlowDao.getUniqueId();
			long pre_id = 0;
			long cur_detail_id = 0;
			// 插入多条bz_auditing_detail
			long[] auditUserArr = {audit1, audit2, audit3, audit4, audit5}; 
			for(long auditUserId : auditUserArr) {
				if(auditUserId > 0) {
					AuditingDetail auditingDetail = new AuditingDetail();
					auditingDetail.setFlow_id(flow_id);
					long auditingDetailId = this.auditingDetailDao.getUniqueId();
					auditingDetail.setId(auditingDetailId);
					auditingDetail.setAudit_id(auditUserId);
					auditingDetail.setCreate_time(nowDate);
					auditingDetail.setPre_id(pre_id);
					this.auditingDetailDao.addAuditingDetail(auditingDetail);
					if(pre_id == 0) {
						cur_detail_id = auditingDetailId;
					}
					pre_id = auditingDetailId;
				}
			}
			
			// 插入一条bz_auditing_flow，
			AuditingFlow auditingFlow = new AuditingFlow();
			auditingFlow.setId(flow_id);
			auditingFlow.setApplication_id(application_id);
			auditingFlow.setCreate_id(user_id);
			auditingFlow.setCreate_time(nowDate);
			auditingFlow.setFlow_type("2"); // 审批流程类型1请假流程2考勤流程3工资流程4加值班补贴流程
			auditingFlow.setFlow_sts("0"); // 流程状态0审核中1结束2作废
			auditingFlow.setCur_detail_id(cur_detail_id);
			this.auditingFlowDao.addAuditingFlow(auditingFlow);
			
			if(saveAndCommit == 1) { // 保存并且直接进行提交
				// 提交审批，设置bz_attend_application的sts为“审批中”
				this.attendApplicationDao.updateAttendApplicationStatus(application_id, "1");
				repMessage.setResponse_code("0");
				repMessage.setResponse_desc("提交审批成功");
			} else { // 保存操作
				repMessage.setResponse_code("0");
				repMessage.setResponse_desc("新增考勤成功");
			}
			
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("新增考勤失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.error("新增考勤失败", e);
		}
		return repMessage;
	}


	@Override
	public RepMessage modifyWorkAtten(long attend_application_id, long dept_id,String dateStr, String[] staff_Ids, String[] schedule_Ids, String[] man_hour_midnights,
			String[] work_values, long audit1, long audit2, long audit3, long audit4, long audit5) {
		// 修改考勤，更新bz_attend_application一条记录，更新bz_attend_record多条数据,
		// 删除旧的bz_auditing_detail,重新插入多条bz_auditing_detail，设置了几个审批人员就有几条记录，记录之间上一流程和下一流程之间互相关联
		
		RepMessage repMessage = new RepMessage();
		try {
		
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat df2 = new SimpleDateFormat("yyyyMM");
			SimpleDateFormat df4 = new SimpleDateFormat("yyyyMMdd");
			Date genDate = df.parse(dateStr);
			genDate.setHours(0);
			genDate.setMinutes(0);
			genDate.setSeconds(0);
			
			long month = DateUtil.getDateMonth(genDate);
			int year = DateUtil.getDateYear(genDate);
			int day = DateUtil.getDateDay(genDate);
			
			long yearMonth = Long.parseLong(df2.format(genDate));
			
			// 更新bz_attend_application一条记录，看原型不需要进行更新日期
			AttendApplication attendApplication = this.attendApplicationDao.getAttendApplicationById(attend_application_id);
			if(attendApplication == null) {
				repMessage.setResponse_code("-2");
				repMessage.setResponse_desc("考勤详情不存在");
				return repMessage;
			}
			
			
			// 删除旧的bz_attend_record,根据dept_id和attend_day
			this.attendRecordDao.deleteAttendRecordByDeptDate(dept_id, genDate);
			
			
			// 获得公司id
			int corp_id = 0;
			if (WorkAttenModuleImp.context.getContextByName("corp_id") != null) {
				  corp_id = Integer.parseInt(WorkAttenModuleImp.context.getContextByName("corp_id").toString());
			}
			
			// 查询某个年份，某个公司的日历
			DayModel yearCalendar = this.workDayDao.queryYearCalendar(corp_id, String.valueOf(year));
			
			// 查询某个日期，属于那种类型的加值班
			DayModel workDay = this.workDayDao.queryForDate(df4.format(genDate), yearCalendar.getId());
			int genDayType = Integer.parseInt(workDay.getDayType());
			int wday_id = Integer.parseInt(workDay.getId());
			
			if(genDayType == 0) { // 法定工作日情况，
				// 判断这个日期是工作日，还是周末，
				// 获得这个日期是星期几
				int dayOfWeek = DateUtil.getDayForWeek(genDate);
				DayModel weekDay = this.workDayDao.queryWeekDay(wday_id, dayOfWeek);
				if(weekDay.getOtimeId().equals("1")) { // 工作日
					
				} else {// 周末, 设置genDayType为4
					genDayType = 4;
				}
			}
			
			// 根据genDayType查询bz_schedule_cfg表所有记录
			List<ScheduleCfg> genDayScheduleList = this.scheduleCfgDao.getScheduleCfgByType(genDayType);
			
			
			// 插入bz_attend_record多条数据
			for(int i = 0; i < staff_Ids.length; i++) {
				String oneStaffId = staff_Ids[i];
				AttendRecord oneAttendRecord = new AttendRecord();
				oneAttendRecord.setCreate_id(attendApplication.getCreate_id());
				oneAttendRecord.setCreate_time(attendApplication.getCreate_time());
				oneAttendRecord.setDept_id(dept_id);
				oneAttendRecord.setAttend_day(genDate);
				oneAttendRecord.setStaff_id(Long.parseLong(oneStaffId));
				oneAttendRecord.setMan_hour_midnight(Long.parseLong(man_hour_midnights[i]));
				oneAttendRecord.setWork_value(work_values[i]);
				
//				oneAttendRecord.setSchedule_id(Long.parseLong(schedule_Ids[i]));
				
				if(schedule_Ids[i] != null && !schedule_Ids[i].isEmpty()) {
					
					// 判断这个员工被勾选的，对应bz_schedule_cfg表中schedule_sub_type包含哪一个，就增加一个这个setSchedule_id的AttendRecord记录
					for(ScheduleCfg oneScheduleCfg : genDayScheduleList) {
						// 判断这个值班子类型，是否被勾选了，如果被勾选了，就增加一条AttendRecord记录
						String[] subTypeArr = oneScheduleCfg.getSchedule_sub_type().split(",");
						for(String oneSubType : subTypeArr) {
							if(schedule_Ids[i].contains(oneSubType)) {
								oneAttendRecord.setSchedule_id(oneScheduleCfg.getId());
								this.attendRecordDao.addAttendRecord(oneAttendRecord);
								break;
							}
						}
					}
				}
			}
			
			AuditingFlow auditingFlow = this.auditingFlowDao.getAuditingFlowByApId(attend_application_id);
			if(auditingFlow != null) {
				// 删除旧的bz_auditing_detail，根据flow_id
				this.auditingDetailDao.deleteAuditingDetailByFlowId(auditingFlow.getId());
				
				long flow_id = auditingFlow.getId();
				long pre_id = 0;
				long cur_detail_id = 0;
				// 重新插入多条bz_auditing_detail
				long[] auditUserArr = {audit1, audit2, audit3, audit4, audit5}; 
				for(long auditUserId : auditUserArr) {
					if(auditUserId > 0) {
						AuditingDetail auditingDetail = new AuditingDetail();
						auditingDetail.setFlow_id(flow_id);
						long auditingDetailId = this.auditingDetailDao.getUniqueId();
						auditingDetail.setId(auditingDetailId);
						auditingDetail.setAudit_id(auditUserId);
						auditingDetail.setCreate_time(auditingFlow.getCreate_time());
						auditingDetail.setPre_id(pre_id);
						this.auditingDetailDao.addAuditingDetail(auditingDetail);
						if(pre_id == 0) {
							cur_detail_id = auditingDetailId;
						}
						pre_id = auditingDetailId;
					}
				}
				
				// 更新一条bz_auditing_flow，更新当前审批明细的id
				auditingFlow.setCur_detail_id(cur_detail_id);
				this.auditingFlowDao.updateAuditingFlow(auditingFlow);
			}
			
			repMessage.setResponse_code("0");
			repMessage.setResponse_desc("修改考勤成功");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("修改考勤失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.error("修改考勤失败", e);
		}
		return repMessage;
	}


	@Override
	public RepMessage commitAudit(long attend_application_id) {
		RepMessage repMessage = new RepMessage();
		try {
			// 提交审批，设置bz_attend_application的sts为“审批中”
			this.attendApplicationDao.updateAttendApplicationStatus(attend_application_id, "1");
			repMessage.setResponse_code("0");
			repMessage.setResponse_desc("提交审批成功");
			
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("提交审批失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.error("提交审批失败", e);
		}
		return repMessage;
	}


	@Override
	public RepMessage revokeAudit(long attend_application_id) {
		RepMessage repMessage = new RepMessage();
		try {
			// 撤回审批，设置bz_attend_application的sts为“初始”
			this.attendApplicationDao.updateAttendApplicationStatus(attend_application_id, "0");
			repMessage.setResponse_code("0");
			repMessage.setResponse_desc("撤回审批成功");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("撤回审批失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.error("撤回审批失败", e);
		}
		return repMessage;
	}


	@Override
	public RepMessage auditWorkAttend(long attend_application_id, String audit_sts, String audit_remark) {
		// 审批考勤，审批通过和审批不通过两种，设置bz_auditing_detail的audit_sts，根据flow_id和audit_id设置
		// 获得当前用户的id,查询bz_attend_application(attend_application_id)关联bz_auditing_flow(flow_id)关联bz_auditing_detail(flow_id)
		RepMessage repMessage = new RepMessage();
		try {
			int staff_id = Integer.parseInt(WorkAttenModuleImp.context.getContextByName("staff_id").toString());
			AuditingFlow auditingFlow = this.auditingFlowDao.getAuditingFlowByApId(attend_application_id);
			if(auditingFlow == null) {
				repMessage.setResponse_code("-2");
				repMessage.setResponse_desc("审批流程不存在");
				return repMessage;
			}
			
			AuditingDetail auditingDetail = this.auditingDetailDao.getAuditingDetailById(auditingFlow.getCur_detail_id());
			if(auditingDetail == null) {
				repMessage.setResponse_code("-3");
				repMessage.setResponse_desc("审批明细记录不存在");
				return repMessage;
			}
			
			auditingDetail.setAudit_sts(audit_sts);
			auditingDetail.setAudit_remark(audit_remark);
			auditingDetail.setAudit_time(new Date());
			this.auditingDetailDao.updateAuditingDetail(auditingDetail);
			
			repMessage.setResponse_code("0");
			repMessage.setResponse_desc("审批考勤成功");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("审批考勤失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.error("审批考勤失败", e);
		}
		return repMessage;
	}


	@Override
	public RepMessage queryWorkAttendList(long dept_id, String audit_sts, Date beginTime, Date endTime, int pageNum,
			int pageSize) {
		// 考勤录入、审批列表，分页查询（根据权限）dept_id, audit_sts, "beginTime", "endTime"
		// 查询bz_attend_application，关联bz_auditing_flow，显示申请项目的具体状态，根据用户权限进行查询
		RepMessage repMessage = new RepMessage();
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			
			Map<String, Object> map = new HashMap();
			map.put("result",
					this.attendApplicationDao.queryAttendApplicationByPage(dept_id, audit_sts, beginTime, endTime, pageNum, pageSize));
			repMessage.setContent(map);
			repMessage.setResponse_code("0");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("条件查询日志失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.warn("条件查询日志失败");
		}
		return repMessage;
	}
	
	@Override
	public RepMessage queryAddWorkAttendList(long dept_id, String audit_sts, Date beginTime, Date endTime, int pageNum,
			int pageSize) {
		// 考勤录入列表，分页查询（根据权限）dept_id, audit_sts, "beginTime", "endTime"
		// 查询bz_attend_application，关联bz_auditing_flow，显示申请项目的具体状态，根据用户权限进行查询
		RepMessage repMessage = new RepMessage();
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			
			String user_id = "";
			user_id = WorkAttenModuleImp.context.getContextByName("user_id").toString();
			
			// 获得用户的roleId,判断是否是管理员可以显示全部列表
			long roleId = this.contactInfoDao.getRoleIdByUserId(Long.parseLong(user_id));
			if(roleId == 1) {
				user_id = "";
			}
			
			Map<String, Object> map = new HashMap();
			map.put("result",
					this.attendApplicationDao.queryAddAttendApplicationByPage(dept_id, audit_sts, beginTime, endTime, pageNum, pageSize, user_id));
			repMessage.setContent(map);
			repMessage.setResponse_code("0");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("条件查询日志失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.warn("条件查询日志失败");
		}
		return repMessage;
	}
	
	
	@Override
	public RepMessage queryAuditWorkAttendList(long dept_id, String audit_sts, Date beginTime, Date endTime, int pageNum,
			int pageSize) {
		// 考勤审批列表，分页查询（根据权限）dept_id, audit_sts, "beginTime", "endTime"
		// 查询bz_attend_application，关联bz_auditing_flow，显示申请项目的具体状态，根据用户权限进行查询
		RepMessage repMessage = new RepMessage();
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			
			Map<String, Object> map = new HashMap();
			String user_id = "";
			user_id = WorkAttenModuleImp.context.getContextByName("user_id").toString();
			
			// 获得用户的roleId,判断是否是管理员可以显示全部列表
			long roleId = this.contactInfoDao.getRoleIdByUserId(Long.parseLong(user_id));
			if(roleId == 1) {
				user_id = "";
			}
			
			map.put("result",
					this.attendApplicationDao.queryAuditAttendApplicationByPage(dept_id, audit_sts, beginTime, endTime, pageNum, pageSize, user_id));
			repMessage.setContent(map);
			repMessage.setResponse_code("0");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("条件查询日志失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.warn("条件查询日志失败");
		}
		return repMessage;
	}


	@Override
	public RepMessage getWorkAttendDetail(long attend_application_id) {
		// 考勤详情查看，查询bz_attend_application,然后再查询bz_attend_record列表 ，根据dept_id和attend_day，
		// 查询bz_attend_application，看这个状态是否已经提交审批，若是已经提交审批，再查询bz_auditing_flow和bz_attend_record
		
		RepMessage repMessage = new RepMessage();
		try {
			AttendApplication attendApplication = this.attendApplicationDao.getAttendApplicationById(attend_application_id);
			if(attendApplication == null) {
				repMessage.setResponse_code("-2");
				repMessage.setResponse_desc("考勤详情不存在");
				return repMessage;
			}
			
			long yearMonth = attendApplication.getAttendance_month();
			String attendDayStr = attendApplication.getAttendance_days();
			
			String attend_dayStr = yearMonth + attendDayStr;
			
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
			Date date = df.parse(attend_dayStr);
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			attendApplication.setAttendanceDayStr(df2.format(date));
			
			
			// 查询bz_attend_record列表，根据dept_id和attend_day
			List<AttendRecord> attendRecordList = this.attendRecordDao.getAttendRecordList(attendApplication.getDept_id(), date);
			
			// 查询bz_auditing_flow
			AuditingFlow auditingFlow = this.auditingFlowDao.getAuditingFlowByApId(attend_application_id);
			
			
			// 查询bz_auditing_detail列表
			List<AuditingDetail> auditingDetailList = this.auditingDetailDao.getAuditingDetailList(auditingFlow.getId());
			
			int flowSts = Integer.parseInt(auditingFlow.getFlow_sts());
			for(AuditingDetail oneAuditDet : auditingDetailList) {
				String auditTxt = "待审批";
				if(StringUtils.isNotEmpty(oneAuditDet.getAudit_sts())) {
					int auditSts = Integer.parseInt(oneAuditDet.getAudit_sts());
					if(auditSts == AuditingDetail.AuditDetailSts.WaitAudit && flowSts == AuditingFlow.FlowSts.Auditing) {
						auditTxt = "待审批";
					} else if(auditSts == AuditingDetail.AuditDetailSts.PassAudit) {
						auditTxt = "通过";
					} else if(auditSts == AuditingDetail.AuditDetailSts.Reject) {
						auditTxt = "拒绝";
					} else if(auditSts == AuditingDetail.AuditDetailSts.Transfer) {
						auditTxt = "转批";
					} else if(auditSts == AuditingDetail.AuditDetailSts.Reject) {
						auditTxt = "已撤回";
					} 
				} 
				
				oneAuditDet.setAudit_stsTxt(auditTxt);
			}
			
			Map<String, Object> map = new HashMap();
			map.put("attendApplication", attendApplication);
			map.put("attendRecordList", attendRecordList);
			
			map.put("auditingFlow", auditingFlow);
			map.put("auditingDetailList", auditingDetailList);
			
			repMessage.setContent(map);
			repMessage.setResponse_code("0");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("查询考勤详情失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.warn("查询考勤详情失败");
		}
		return repMessage;
	}
	
	@Override
	public RepMessage getWorkAttendDetailByDay(long dept_id, String monthStr, String searchStr, int pageNum, int pageSize) {
		// 考勤详情查看，查询bz_attend_application,然后再查询bz_attend_record列表 ，根据dept_id和attend_day，
		// 查询bz_attend_application，看这个状态是否已经提交审批，若是已经提交审批，再查询bz_auditing_flow和bz_attend_record
		RepMessage repMessage = new RepMessage();
		try {
			// 根据日期查询
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat df3 = new SimpleDateFormat("dd");
			SimpleDateFormat df4 = new SimpleDateFormat("yyyyMM");
			
			Date genDate = df2.parse(monthStr);
			genDate.setHours(0);
			genDate.setMinutes(0);
			genDate.setSeconds(0);
			
			long yearMonth = Long.parseLong(df4.format(genDate));
			String attendance_days = df3.format(genDate);
			
			AttendApplication attendApplication = this.attendApplicationDao.getAttendApplicationByDay(dept_id, yearMonth, attendance_days);
			
			if(attendApplication == null) {
				repMessage.setResponse_code("-2");
				repMessage.setResponse_desc("考勤详情不存在");
				return repMessage;
			}
			long attend_application_id = attendApplication.getId();
			
			String attendDayStr = attendApplication.getAttendance_days();
			String attend_dayStr = yearMonth + attendDayStr;
			
			Date date = df.parse(attend_dayStr);
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			attendApplication.setAttendanceDayStr(df2.format(date));
			
			
			// 可优化，只查询用户列表对应的MemberInfo的id的列表
			List<MemberInfo> memberList = this.contactInfoDao.getMemberListByDept(dept_id, searchStr, (int)pageNum, (int)pageSize);
			List<Long> memberIdList = new ArrayList<Long>();
			for(MemberInfo oneMember : memberList) {
				memberIdList.add(oneMember.getId());
			}
			
			// 查询bz_attend_record列表，根据dept_id和attend_day
//			List<AttendRecord> attendRecordList = this.attendRecordDao.getAttendRecordList(attendApplication.getDept_id(), date);
			List<AttendRecord> attendRecordList = new ArrayList<AttendRecord>();
			if(memberIdList.size() > 0) {
				attendRecordList = this.attendRecordDao.getAttendRecordListByPage(attendApplication.getDept_id(), date, pageNum, pageSize, memberIdList);
			}
			// long total = this.attendRecordDao.getAttendRecordCount(attendApplication.getDept_id(), date);
			
			// 查询bz_auditing_flow
			AuditingFlow auditingFlow = this.auditingFlowDao.getAuditingFlowByApId(attend_application_id);
			
			
			// 查询bz_auditing_detail列表
			List<AuditingDetail> auditingDetailList = this.auditingDetailDao.getAuditingDetailList(auditingFlow.getId());
			
			int flowSts = Integer.parseInt(auditingFlow.getFlow_sts());
			for(AuditingDetail oneAuditDet : auditingDetailList) {
				String auditTxt = "待审批";
				if(StringUtils.isNotEmpty(oneAuditDet.getAudit_sts())) {
					int auditSts = Integer.parseInt(oneAuditDet.getAudit_sts());
					if(auditSts == AuditingDetail.AuditDetailSts.WaitAudit && flowSts == AuditingFlow.FlowSts.Auditing) {
						auditTxt = "待审批";
					} else if(auditSts == AuditingDetail.AuditDetailSts.PassAudit) {
						auditTxt = "通过";
					} else if(auditSts == AuditingDetail.AuditDetailSts.Reject) {
						auditTxt = "拒绝";
					} else if(auditSts == AuditingDetail.AuditDetailSts.Transfer) {
						auditTxt = "转批";
					} else if(auditSts == AuditingDetail.AuditDetailSts.Reject) {
						auditTxt = "已撤回";
					} 
				} 
				
				oneAuditDet.setAudit_stsTxt(auditTxt);
			}
			
			Map<String, Object> map = new HashMap();
			map.put("attendApplication", attendApplication);
			map.put("attendRecordList", attendRecordList);
			
			map.put("auditingFlow", auditingFlow);
			map.put("auditingDetailList", auditingDetailList);
			
			//map.put("total", total);
			
			repMessage.setContent(map);
			repMessage.setResponse_code("0");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("查询考勤详情失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.error("查询考勤详情失败", e);
			e.printStackTrace();
		}
		return repMessage;
	}


	
	@Override
	public RepMessage getExportWorkAttend(long dept_id, String monthStr) {
		// 考勤导出，导出某个部门，某个月份的所有员工考勤信息
		RepMessage repMessage = new RepMessage();
		try {
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
			SimpleDateFormat df2 = new SimpleDateFormat("dd");
			Date monthDate = df.parse(monthStr);
			Date monthStartTime = DateUtil.getMonthStartTime(monthDate);
			Date monthEndTime = DateUtil.getMonthEndTime(monthDate);
			int endDay = monthEndTime.getDate();
			
			
			// 查询某个部门所有的员工列表
			List<MemberInfo> memberList = this.contactInfoDao.getMemberListByDept(dept_id, null, 0, 0);
			
			
			// 查询某个部门这个月份所有的考勤信息列表
			List<AttendRecord> attendRecordList = this.attendRecordDao.getDeptMonthAttendRecordList(dept_id, monthStartTime, monthEndTime);
			
			HashMap<String, AttendRecord> attendRecordMap = new HashMap<String, AttendRecord>();
			// 组织成一个返回数组
			
			for(AttendRecord oneAtten : attendRecordList) {
				String oneKey = oneAtten.getStaff_id() + "_" + df2.format(oneAtten.getAttend_day());
				attendRecordMap.put(oneKey, oneAtten);
			}

			List<String[]> retList = new ArrayList<String[]>();
			
			int oneRecLenth = (endDay * 6) + 3;
			for(MemberInfo oneMember : memberList) {
				String[] oneMonthRecArr = new String[oneRecLenth];
				oneMonthRecArr[0] = oneMember.getName();
				oneMonthRecArr[1] = oneMember.getIdcard();
				oneMonthRecArr[2] = oneMember.getDept();
				
				int arrIndex = 3;
				for(int i = 1; i <= endDay; i++) {
					String dayStr = ""+ i;
					if(i < 10) {
						dayStr = "0" + i;
					}
					String oneKey = oneMember.getId() + "_" + dayStr;
					if(attendRecordMap.get(oneKey) != null) {// 该员工有这个日期考勤
						
						AttendRecord oneAtten = attendRecordMap.get(oneKey);
						oneMonthRecArr[arrIndex] = "";
						oneMonthRecArr[arrIndex + 1] = "";
						oneMonthRecArr[arrIndex + 2] = "";
						oneMonthRecArr[arrIndex + 3] = "";
						oneMonthRecArr[arrIndex + 4] = oneAtten.getWork_value();
						oneMonthRecArr[arrIndex + 5] = oneAtten.getMan_hour_midnight() + "";
						
						String checkType = oneAtten.getScheduleCheckType();
						if(checkType.contains("1")) {
							oneMonthRecArr[arrIndex] = "√";
						} 
						if(checkType.contains("2")) {
							oneMonthRecArr[arrIndex + 1] = "√";
						} 
						if(checkType.contains("4")) {
							oneMonthRecArr[arrIndex + 2] = "√";
						} 
						if(checkType.contains("8")) {
							oneMonthRecArr[arrIndex + 3] = "√";
						} 
					} else { // 该员工没有这个日期的考勤
						oneMonthRecArr[arrIndex] = "";
						oneMonthRecArr[arrIndex + 1] = "";
						oneMonthRecArr[arrIndex + 2] = "";
						oneMonthRecArr[arrIndex + 3] = "";
						oneMonthRecArr[arrIndex + 4] = "0";
						oneMonthRecArr[arrIndex + 5] = "0";
					}
					arrIndex = arrIndex + 6;
				}
				retList.add(oneMonthRecArr);
			}
			
			Map<String, Object> map = new HashMap();
			map.put("result", retList);
			repMessage.setContent(map);
			repMessage.setResponse_code("0");
		} catch (Exception e) {
			repMessage.setResponse_code("-1");
			repMessage.setResponse_desc("条件查询日志失败");
			repMessage.setResponse_detail(e.getLocalizedMessage());
			logger.warn("条件查询日志失败");
		}
		return repMessage;
	}
	
}
